import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:media_kit_video/media_kit_video.dart';
import 'package:pornhub_app/assets/assets.dart';
import 'package:pornhub_app/components/diolog/loading/loading_view.dart';
import 'package:pornhub_app/components/image_view.dart';
import 'package:pornhub_app/components/rich_text_view.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/generate/app_image_path.dart';
import 'package:pornhub_app/http/api/api.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/utils/ad_jump.dart';
import 'package:pornhub_app/utils/app_utils.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/utils/utils.dart';
import 'package:pornhub_app/views/player/views/av_player_loading.dart';
import 'package:pornhub_app/views/player/views/comment_list.dart';
import 'package:visibility_detector/visibility_detector.dart';

import '../../model/community/community_model.dart';
import '../../views/player/play_center_dispatch.dart';
import 'package:pornhub_app/views/player/views/media_kit_custom_controls.dart'
    as custom;

class CommunityCell extends StatefulWidget {
  final CommunityModel model;
  final bool isDetail;
  final Function(List<String> images, int index)? imageOnTap; //评论点击事件

  const CommunityCell(
      {super.key, required this.model, this.imageOnTap, this.isDetail = false});

  @override
  createState() => _CommunityCellState();
}

class _CommunityCellState extends State<CommunityCell> {
  RxBool isLike = false.obs;
  RxInt likeNumber = 0.obs;

  @override
  void initState() {
    super.initState();
    isLike.value = widget.model.isLike ?? false;
    likeNumber.value = widget.model.realLikes ?? 0;
  }

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.only(
          left: 15.w,
          right: 15.w,
          bottom: 15.w,
          top: widget.isDetail ? 0 : 15.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          ///用户的信息 详情
          _buildUserInfoView(),
          8.verticalSpace,

          ///标题内容
          RichTextView(
            text: widget.model.coteries != null &&
                    widget.model.coteries!.isNotEmpty &&
                    widget.model.coteries!.first.name != null &&
                    widget.model.coteries!.first.name!.isNotEmpty
                ? "/${widget.model.coteries?.first.name}/${widget.model.content}"
                : "${widget.model.content}",
            style: TextStyle(color: COLOR.color_A1A1A1, fontSize: 14.w),
            highlightStyle:
                TextStyle(color: COLOR.color_FF9000, fontSize: 14.w),
            specifyTexts: [
              widget.model.coteries != null &&
                      widget.model.coteries!.isNotEmpty &&
                      widget.model.coteries!.first.name != null &&
                      widget.model.coteries!.first.name!.isNotEmpty
                  ? "/${widget.model.coteries?.first.name}/"
                  : ""
            ],
            onTap: (value) {
              if (value == "/${widget.model.coteries?.first.name}/") {
                ///需要切换tab
              } else {
                jumpExternalAddress(value, null);
              }
            },
          ),
          10.verticalSpace,

          ///图片、或者视频
          widget.model.dynamicType == 2 ? _buildVideoView() : _buildImageView(),
          13.verticalSpace,

          ///操作
          _buildOperateView(),
        ],
      ).onOpaqueTap(() => Get.toCommunityDetail(
            dynamicId: widget.model.dynamicId ?? 0,
            dynamicModel: widget.model,
          )),
    );
  }

  _buildUserInfoView() {
    return Row(
      children: [
        ImageView(
          src: widget.model.logo ?? "",
          width: 44.w,
          height: 44.w,
          defaultPlace: Assets.avatarplaceholer,
          borderRadius: BorderRadius.circular(22.w),
        ).onOpaqueTap(() => Get.toUserHome(userId: widget.model.userId ?? 0)),
        10.horizontalSpace,
        Expanded(
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                TextView(
                  text: '${widget.model.nickName?.trim()}',
                  color: COLOR.white,
                  fontSize: 16.w,
                  fontWeight: FontWeight.w600,
                ),
                6.horizontalSpace,
                (widget.model.vipType ?? 0) > 0 &&
                        AppUtils.getVipTypeToImagePath(
                                widget.model.vipType ?? 0)
                            .isNotEmpty
                    ? ImageView(
                        src: AppUtils.getVipTypeToImagePath(
                            widget.model.vipType ?? 0),
                        height: 15.w,
                        fit: BoxFit.fitHeight,
                      )
                    : const SizedBox.shrink(),
              ],
            ),
            TextView(
              text: Utils.dateAgo(widget.model.createdAt ?? ""),
              color: COLOR.white,
              fontSize: 12.w,
            ),
          ],
        )),
      ],
    );
  }

  _buildVideoRenderView(PlayCenterDispatch dispatcher) {
    final themColor = COLOR.hexColor("#ff960f");
    final videoH = 180.w;
    final controls = MaterialVideoControlsTheme(
      normal: MaterialVideoControlsThemeData(
        seekBarPositionColor: themColor,
        seekBarThumbColor: themColor,
      ),
      fullscreen: MaterialVideoControlsThemeData(
        seekBarPositionColor: themColor,
        seekBarThumbColor: themColor,
      ),
      child: custom.MediaKitCustomControls(
        buildContext: context,
        hideBack: true,
        viewSize: Size(Get.width, videoH),
        texturePos: Rect.fromLTWH(0, 0, Get.width, videoH),
      ),
    );
    if (kIsWeb) {
      return Video(
        key: Key(dispatcher.playPath),
        controller: dispatcher.playerVC!,
        filterQuality: FilterQuality.none,
        controls: (__) => controls,
      );
    }
    return Video(
      key: Key(dispatcher.playPath),
      filterQuality: FilterQuality.none,
      controller: dispatcher.playerVC!,
      controls: (__) => controls,
    );
  }

  _buildVideoView() {
    final dispatcher = Get.find<PlayCenterDispatch>();
    return VisibilityDetector(
      key: Key('${widget.model.dynamicId ?? 0}'),
      child: Container(
        height: 180.w,
        color: COLOR.color_959595,
        alignment: Alignment.center,
        child: ListenableBuilder(
          listenable: dispatcher,
          builder: (context, child) {
            final playPath = widget.model.video?.videoUrl ?? '';
            final isme = dispatcher.playPath.isNotEmpty &&
                dispatcher.playPath == playPath;
            return SizedBox(
              width: double.infinity,
              height: double.infinity,
              child: Stack(
                alignment: Alignment.center,
                children: [
                  //封面
                  ImageView(
                    src: widget.model.video?.coverImg?.first ?? "",
                    width: Get.width,
                    height: 180.w,
                  ),

                  ///播放按钮
                  Image.asset(
                    AppImagePath.short_short_play_btn,
                    width: 44.w,
                    height: 44.w,
                  ).onTap(() {
                    final playPath = widget.model.video?.videoUrl ?? '';
                    if (playPath.isEmpty) return;
                    dispatcher.changePlayerSource(playPath);
                  }),
                  Visibility(
                    visible: isme,
                    child: Positioned.fill(
                      child: dispatcher.playerInitialized
                          ? _buildVideoRenderView(dispatcher)
                          : const AvPlayerLoading(),
                    ),
                  ),
                ],
              ),
            );
          },
        ),
      ).onTap(() {
        Get.toCommunityDetail(
          dynamicId: widget.model.dynamicId ?? 0,
          dynamicModel: widget.model,
        );
      }),
      onVisibilityChanged: (info) {
        if (info.visibleFraction < 1.0) {
          dispatcher.resetPlayer();
        }
      },
    );
  }

  _buildImageView() {
    List<String> images = widget.model.dynamicImg ?? [];
    if (images.isEmpty) {
      return const SizedBox.shrink();
    } else {
      if (images.length == 1) {
        return ImageView(
          src: images.first,
          width: double.infinity,
          height: 190.w,
          fit: BoxFit.cover,
          borderRadius: BorderRadius.circular(6.w),
        ).onOpaqueTap(() => widget.imageOnTap != null
            ? widget.imageOnTap?.call(images, 0)
            : Get.toCommunityDetail(
                dynamicId: widget.model.dynamicId ?? 0,
                dynamicModel: widget.model,
              ));
      }
      if (images.length == 2) {
        return Row(
          children: [
            Expanded(
              flex: 1,
              child: ImageView(
                src: images.first,
                width: double.infinity,
                height: 162.w,
                fit: BoxFit.cover,
                borderRadius: BorderRadius.circular(6.w),
              ).onOpaqueTap(() => widget.imageOnTap != null
                  ? widget.imageOnTap?.call(images, 0)
                  : Get.toCommunityDetail(
                      dynamicId: widget.model.dynamicId ?? 0,
                      dynamicModel: widget.model,
                    )),
            ),
            8.horizontalSpace,
            Expanded(
              flex: 1,
              child: ImageView(
                src: images.last,
                width: double.infinity,
                height: 162.w,
                fit: BoxFit.cover,
                borderRadius: BorderRadius.circular(6.w),
              ).onOpaqueTap(() => widget.imageOnTap != null
                  ? widget.imageOnTap?.call(images, 1)
                  : Get.toCommunityDetail(
                      dynamicId: widget.model.dynamicId ?? 0,
                      dynamicModel: widget.model,
                    )),
            ),
          ],
        );
      }
      if (images.length > 2) {
        return GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: images.length > 9 ? 9 : images.length,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            crossAxisSpacing: 8.w,
            mainAxisSpacing: 8.w,
          ),
          itemBuilder: (BuildContext context, int index) {
            return ImageView(
              src: images[index],
              width: double.infinity,
              height: 106.w,
              fit: BoxFit.cover,
              borderRadius: BorderRadius.circular(6.w),
            ).onOpaqueTap(() => widget.imageOnTap != null
                ? widget.imageOnTap?.call(images, index)
                : Get.toCommunityDetail(
                    dynamicId: widget.model.dynamicId ?? 0,
                    dynamicModel: widget.model,
                  ));
          },
        );
      }
    }
  }

  _buildOperateView() {
    return Row(
      children: [
        Expanded(
          flex: 1,
          child: Obx(() => _buildOperateitemView(
                  isLike.value
                      ? AppImagePath.community_like_s
                      : AppImagePath.community_like,
                  Utils.numFmt(likeNumber.value)))
              .onOpaqueTap(() => likeOrCanelLike()),
        ),
        Expanded(
          flex: 1,
          child: _buildOperateitemView(AppImagePath.community_chat,
                  "${widget.model.commentNum ?? 0}")
              .onOpaqueTap(() => widget.isDetail ? () {} : showCommentDialog()),
        ),
        Expanded(
          flex: 1,
          child: _buildOperateitemView(AppImagePath.community_share, "分享")
              .onOpaqueTap(() => Get.toShare()),
        ),
      ],
    );
  }

  Widget _buildOperateitemView(String imagePath, String title) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        ImageView(
          src: imagePath,
          height: 18.w,
          fit: BoxFit.fill,
        ),
        3.horizontalSpace,
        TextView(
          text: title,
          color: COLOR.white,
          fontSize: 12.w,
        ),
      ],
    );
  }

  ///点赞或者取消点赞
  likeOrCanelLike() {
    LoadingView.singleton.wrap(
        context: context,
        asyncFunction: () async {
          Api.likeOrCancelLike(
                  isLike: !isLike.value, dynamicId: widget.model.dynamicId ?? 0)
              .then((response) {
            if (response) {
              likeNumber.value =
                  isLike.value ? likeNumber.value - 1 : likeNumber.value + 1;
              isLike.value = !isLike.value;
            }
          });
        });
  }

  showCommentDialog() {
    Get.bottomSheet(
      Container(
        height: MediaQuery.of(context).size.height * 2 / 3,
        color: COLOR.color_161616,
        child: Column(
          children: [
            10.verticalSpace,
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                32.horizontalSpace,
                Expanded(
                  child: Center(
                    child: TextView(
                      text: "全部评论(${widget.model.commentNum ?? 0})",
                      color: COLOR.white,
                      fontSize: 18.w,
                    ),
                  ),
                ),
                Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 18.w,
                ),
                14.horizontalSpace,
              ],
            ),
            Expanded(
              child: PlayCommentList(
                dynamicId: widget.model.dynamicId,
                type: CommentTypeEnumValue.circle,
              ),
            ),
          ],
        ),
      ),
      isDismissible: true,
      isScrollControlled: true,
    );
  }
}
